package at.jku.ce.brokerplatform;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;



/**
 * Servlet implementation class Login
 */
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet() 
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		boolean dataOK = false;
		for (User u : Users.getAllUsers()) {
			if (u.getUsername().equals(request.getParameter("user"))) {
				if (u.getPassword().equals(request.getParameter("pwd"))) {
					dataOK = true;
				}
			}
		}
		
		if (dataOK) {	
			System.out.println("login erfolgreich");
		
			String user = request.getParameter("user");
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
			//setting session to expiry in 60 mins
            session.setMaxInactiveInterval(60*60);
            Cookie userName = new Cookie("user", user);
            userName.setMaxAge(60*60);
            response.addCookie(userName);
            response.sendRedirect("depotmanagement.jsp");
	
		} else {
			System.out.println("login fehlgeschlagen");
			
            //v1
            //response.sendRedirect("index.jsp?login=failed");	
            
            //v2
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
            PrintWriter out = response.getWriter();
            out.println("<font color=red>Benutzername oder Passwort sind falsch. Bitte erneut versuchen.</font>");
            rd.include(request, response);
		}
	}
	
}
